<template>
  <div id="uploadSingImg">
    <el-upload
      class="avatar-uploader"
      action="#"
      :accept="accept"
      :show-file-list="false"
      :auto-upload="false"
      :on-change="changeUpload"
      :disabled="disabled"
    >
      <div v-if="cover" class="el-img-box">
        <template v-if="showDeleteIcon">
          <i class="icon del el-icon-delete" @click="deleteImg($event)"></i>
          <el-image
            :src="cover"
            class="avatar"
            fit="contain"
            :preview-src-list="previewSrc"
            @click="previewImg($event)"
          />
        </template>
        <el-image v-else :src="cover" class="avatar" fit="contain" />
      </div>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <div slot="tip" class="el-upload__tip">
        <!--此处放置图片规格说明-->
        <slot name="imgInfo"></slot>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { uploadImg, uploadImgPolyv } from '@/api/common/img'
export default {
  name: 'UploadSingImg',
  msg: '上传单独图片',
  props: {
    imgUrl: {
      type: String,
      default: function() {
        return ''
      }
    },
    maxSize: {
      //图片最大尺寸，默认2M
      type: Number,
      default: function() {
        return 2
      }
    },
    accept: {
      //上传图片支持格式
      type: String,
      default: function() {
        return '.jpg'
      }
    },
    disabled: {
      //是否可编辑，默认可以
      type: Boolean,
      default: function() {
        return false
      }
    },
    showDeleteIcon: {
      //是否显示删除按钮，默认隐藏
      type: Boolean,
      default: function() {
        return false
      }
    },
    uploadPolyv: {
      //是否使用保利威上传封面
      type: Object,
      default: function() {
        return {
          isPolyv: false,
          vid: ''
        }
      }
    },
    WHScale: {
      //图片 宽度/高度  比例;比例不是整数的情况下，返回一个区间值。
      // 大于 WHScale[0] && 小于 WHScale[1]
      type: Array,
      default: function() {
        return []
      }
    }
  },
  computed: {
    previewSrc() {
      let ary = [this.cover]
      return ary
    }
  },
  data() {
    return {
      cover: ''
    }
  },
  watch: {
    imgUrl: {
      handler(newVal) {
        this.cover = this.imgUrl
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.cover = this.imgUrl
  },
  methods: {
    /* 重新上传 */
    // clearList() {
    //   this.fileList = []
    //   this.cover = ''
    //   this.$emit('getGoodImg', '')
    // },
    /*预览*/
    previewImg(e = null) {
      //阻止冒泡事件
      if (e) {
        e.stopPropagation()
      }
      setTimeout(() => {
        let imgDom = document.getElementsByClassName(
          'el-image-viewer__wrapper'
        )[0]
        imgDom.addEventListener('click', function(e) {
          if (e) {
            e.stopPropagation()
          }
        })
        let markDom = document.getElementsByClassName(
          'el-image-viewer__mask'
        )[0]
        markDom.addEventListener('click', function(e) {
          if (e) {
            e.stopPropagation()
          }
        })
      }, 1)
    },
    /*封面图上传*/
    async changeUpload(file, fileList) {
      let flog = await this.beforeUpload(file.raw)
      if (!flog) return
      let formData = new FormData()
      formData.append('file', file.raw)
      if (this.uploadPolyv.isPolyv) {
        //保利威上传
        if (!this.uploadPolyv.vid) {
          this.$message.warning('请先上传视频！')
          return
        }
        formData.append('vid', this.uploadPolyv.vid)
        uploadImgPolyv(
          formData,
          (response) => {
            this.$emit('getImgUrl', response)
            this.cover = response
          },
          (response) => {
            this.loading = false
            this.$message.warning(response.message)
          }
        )
      } else {
        //OSS上传
        uploadImg(
          formData,
          (response) => {
            this.$emit('getImgUrl', response[0].url)
            this.cover = response[0].url
          },
          (response) => {
            this.loading = false
            this.$message.warning(response.message)
          }
        )
      }
    },
    countScale(file) {
      return new Promise((resolve, reject) => {
        const _URL = window.URL || window.webkitURL
        let _this = this
        let myImg = new Image()
        myImg.src = _URL.createObjectURL(file)
        myImg.onerror = function() {}
        myImg.onload = function() {
          let [w, h] = [myImg.width, myImg.height]
          let scale = w / h.toFixed(2)
          /*console.log('w=' + w + '   h=' + h)
          console.log(scale)*/
          if (scale > _this.WHScale[0] && scale < _this.WHScale[1]) {
            resolve(true)
          } else {
            resolve(false)
          }
        }
      })
    },
    async beforeUpload(file) {
      let text = ''
      //校验大小
      let isLt2M = true
      if (this.maxSize >= 1) {
        //this.maxSize大于1，以M为单位
        isLt2M = file.size / 1024 / 1024 < this.maxSize
        if (!isLt2M) {
          text += `上传图片大小不能超过 ${this.maxSize}MB!`
        }
      } else {
        //this.maxSize大于1，以KB为单位
        let maxKB = this.maxSize * 1000
        isLt2M = file.size / 1024 < maxKB
        if (!isLt2M) {
          text += `上传图片大小不能超过 ${maxKB}KB!`
        }
      }
      let isScale = true
      //获取图片宽高
      if (this.WHScale.length > 0) {
        isScale = await this.countScale(file)
        /*console.log('isScale=' + isScale)*/
        if (!isScale) {
          text += `请调整图片比例，限制${this.WHScale[2]} !`
        }
      }
      //校验格式
      let acceptAry = this.accept.split(',')
      let newAry = acceptAry.map((item) => {
        let cur = item.substring(1)
        if (cur === 'jpg') {
          cur = 'jpeg'
        }
        return cur
      })
      let isType = false
      for (let item of newAry) {
        if (file.type === `image/${item}`) {
          isType = true
          break
        }
      }
      if (!isType) {
        text += ` 上传文件需为 ${this.accept} 格式!`
      }

      if (!isType || !isLt2M || !isScale) {
        this.$message.error(text)
      }
      return isType && isLt2M && isScale
    },
    /*删除图片*/
    deleteImg(e = null) {
      //阻止冒泡事件
      if (e) {
        e.stopPropagation()
      }
      this.cover = ''
      this.$emit('getImgUrl', '')
    }
  }
}
</script>

<style lang="less">
@ImgW: 178px;
@ImgH: 178px;
#uploadSingImg {
  .avatar-uploader .el-upload {
    width: @ImgW;
    height: @ImgH;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: @ImgW;
    height: @ImgH;
    line-height: @ImgH;
    text-align: center;
  }
  .el-image.avatar {
    width: @ImgW;
    height: @ImgH;
  }
  .el-upload__tip {
    line-height: 16px;
    color: #f00;
    margin-top: 0;
  }
  i.icon {
    position: absolute;
    right: 0;
    top: 0;
    width: 30px;
    height: 30px;
    background: rgba(29, 200, 164, 0.8);
    z-index: 1;
    color: #fff;
    text-align: center;
    line-height: 30px;
    &.del {
      top: auto;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
      z-index: 1000;
    }
  }
}
</style>
